package cn.qiyu5522.tk_ems.controller.admin;

import cn.qiyu5522.tk_ems.exception.BusinessException;
import cn.qiyu5522.tk_ems.result.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * @ProjectName: tk_ems
 * @Package: cn.qiyu5522.tk_ems.controller.admin
 * @ClassName: UploadController
 * @Author: [Toneky]
 * @Date: 2023/3/2 16:00
 * @Version: V1.0
 **/
@Api(tags = "文件上传")
@RestController
@RequestMapping("/admin/upload")
public class UploadController {

    @Value("${upload.file-path}")
    private String filePath;

    @ApiOperation("图片上传")
    @PostMapping("/avatar")
    public R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            throw new BusinessException("上传文件不能为空");
        }
        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        File upload = new File(filePath);//这里只是参考演示、路径建议写在配置文件里面
        if (!upload.exists())
            upload.mkdirs();
        String fileName = new Date().getTime() + "." + fileExt;
        File dest = new File(upload + "/" + fileName);
        // 得到 项目中图片存储的路径
        File path = new File("E:\\IDEAProjects5\\tk_ems\\service-core\\target\\classes\\static\\" + fileName);//这里只是参考演示、路径建议写在配置文件里面
        try {
            //  存放到target
            FileUtils.writeByteArrayToFile(path, file.getBytes());
            // 持久化至本地
            file.transferTo(dest);
            return R.ok().message("上传成功").data("originalFilename", file.getOriginalFilename())
                    .data("fileName", fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.error().message("上传失败,请联系管理员");
    }
}
